import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:series_play/bean/local_video_data.dart';
import 'package:series_play/comm/base/base_state.dart';
import 'package:series_play/generated/assets.dart';
import 'package:series_play/utils/log.dart';
import 'package:series_play/widget/app_image.dart';
import 'package:series_play/widget/video/app_video_info_panel.dart';
import 'package:series_play/widget/video/controller/base_feed_video_controller.dart';

import 'package:media_kit_video/media_kit_video.dart';
import 'package:media_kit/media_kit.dart';

import '../app_color.dart';
import 'controller/app_video_info_controller.dart';

class AppVideoView extends StatefulWidget {
  const AppVideoView({
    required this.pageController,
    required this.index,
    required this.baseFeedVideoController,
    super.key,
  });

  final PageController pageController;
  final int index;
  final BaseFeedVideoController baseFeedVideoController;

  @override
  State<AppVideoView> createState() => _AppVideoViewState();
}

class _AppVideoViewState
    extends BaseControllerState<AppVideoView, AppVideoInfoController> {
  BaseFeedVideoController get mGetController => widget.baseFeedVideoController;

  List<LocalVideoData> get dataList => mGetController.dataList;

  LocalVideoData get data => dataList[widget.index];

  VideoController get videoController =>
      mGetController.controllers[widget.index]!;

  Player get player => mGetController.players[widget.index]!;

  @override
  AppVideoInfoController createController() {
    return AppVideoInfoController();
  }

  @override
  String? getControllerTag() {
    return '${widget.index}';
  }

  @override
  Widget buildPage(BuildContext context) {
    Log.e('创建', "${widget.index}");
    return GestureDetector(
      onTap: () {
        mGetController.switchPlay();
      },
      child: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            // 播放器 最底层
            Positioned.fill(
              child: Video(
                controller: videoController,
                fit: BoxFit.fitWidth,
                controls: NoVideoControls,
              ),
            ),

            Positioned(
              left: 14.w,
              right: 14.w,
              bottom: 0,
              child: IgnorePointer(
                ignoring: false, // 允许拖动
                child: Obx(() {
                  final pos =
                      mGetController.positions[widget.index]?.value ??
                      Duration.zero;
                  final dur =
                      mGetController.durations[widget.index]?.value ??
                      Duration.zero;

                  final max = dur.inMilliseconds.toDouble();
                  final value = pos.inMilliseconds.clamp(0, max).toDouble();

                  return SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      trackHeight: 3.w,
                      overlayShape: SliderComponentShape.noOverlay,
                      // 去掉水波纹
                      thumbShape: CustomThumbShape(4.0),
                      trackShape: UniformTrackShape(),
                      thumbColor: Colors.white,
                      inactiveTrackColor: Colors.white10,
                      activeTrackColor: AppColor.white,
                    ),
                    child: Slider(
                      min: 0,
                      max: max <= 0 ? 1 : max,
                      value: value,
                      onChanged: (v) {},
                    ),
                  );
                }),
              ),
            ),

            // 控制器 中间层 封面
            // Obx(() {
            //   return Center(
            //     child: // 封面渐隐
            //     AnimatedOpacity(
            //       opacity: widget.baseFeedVideoController.isPlaying.value
            //           ? 1.0
            //           : 0.0,
            //       duration: const Duration(milliseconds: 700),
            //       child: Image.network(
            //         data,
            //         fit: BoxFit.cover,
            //         errorBuilder: (_, __, ___) => Container(color: Colors.black),
            //       ),
            //     ),
            //   );
            // }),
            // 操作面板 上层
            Positioned.fill(child: AppVideoInfoPanel('')),

            Obx(() {

              // 当暂停显示时，opacity = 1，缩放到 1.0
              // 播放时，opacity = 0，缩放到 0.8
              final double scale = mGetController.userPaused.value ? 1.0 : 0.8;
              final double opacity = mGetController.userPaused.value ? 1.0 : 0.0;

              return AnimatedOpacity(
                duration: const Duration(milliseconds: 400),
                opacity: opacity,
                curve: Curves.easeInOut,
                child: AnimatedScale(
                  scale: scale,
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeOutBack, // 弹性效果
                  child: Center(
                    child: AppImage(Assets.imagesIcVideoPause, size: 92),
                  ),
                ),
              );

            }),
          ],
        ),
      ),
    );
  }

  @override
  bool hideAppbar() => true;

  @override
  bool get wantKeepAlive => false;

  @override
  bool safeAreaFormTop() => false;

  @override
  bool safeAreaFormBottom() => false;
}

class CustomThumbShape extends SliderComponentShape {
  final double thumbRadius;

  CustomThumbShape(this.thumbRadius);

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size.fromRadius(thumbRadius);
  }

  @override
  void paint(
    PaintingContext context,
    Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter? labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
  }) {
    final Canvas canvas = context.canvas;

    final paint = Paint()
      ..color = sliderTheme.thumbColor ?? Colors.white
      ..style = PaintingStyle.fill;

    canvas.drawCircle(center, thumbRadius, paint);
  }
}

class UniformTrackShape extends RoundedRectSliderTrackShape {
  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    Offset? secondaryOffset,
    bool isEnabled = false,
    bool isDiscrete = false,
    double additionalActiveTrackHeight = 2,
  }) {
    // 统一 active 和 inactive 高度
    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );
    final Paint activePaint = Paint()..color = sliderTheme.activeTrackColor!;
    final Paint inactivePaint = Paint()
      ..color = sliderTheme.inactiveTrackColor!;

    // active track
    final Rect activeRect = Rect.fromLTRB(
      trackRect.left,
      trackRect.top,
      thumbCenter.dx,
      trackRect.bottom,
    );
    context.canvas.drawRRect(
      RRect.fromRectAndRadius(
        activeRect,
        Radius.circular(trackRect.height / 2),
      ),
      activePaint,
    );

    // inactive track
    final Rect inactiveRect = Rect.fromLTRB(
      thumbCenter.dx,
      trackRect.top,
      trackRect.right,
      trackRect.bottom,
    );
    context.canvas.drawRRect(
      RRect.fromRectAndRadius(
        inactiveRect,
        Radius.circular(trackRect.height / 2),
      ),
      inactivePaint,
    );
  }
}
